<template>
  <div class="register-container">
    <div class="register-left">
      <div class="register-form">
        <h1>用户注册</h1>
        <el-form 
          ref="registerFormRef" 
          :model="registerForm" 
          :rules="registerRules" 
          label-width="0px"
          @submit.prevent="handleRegister"
        >
          <el-form-item prop="username">
            <el-input 
              v-model="registerForm.username" 
              placeholder="请输入用户名"
              prefix-icon="User"
              size="large"
              clearable
            />
          </el-form-item>
          
          <el-form-item prop="email">
            <el-input 
              v-model="registerForm.email" 
              placeholder="请输入邮箱"
              prefix-icon="Message"
              size="large"
              clearable
            />
          </el-form-item>
          
          <el-form-item prop="password">
            <el-input 
              v-model="registerForm.password" 
              type="password" 
              placeholder="请输入密码"
              prefix-icon="Lock"
              size="large"
              show-password
            />
          </el-form-item>
          
          <el-form-item prop="confirmPassword">
            <el-input 
              v-model="registerForm.confirmPassword" 
              type="password" 
              placeholder="请确认密码"
              prefix-icon="Lock"
              size="large"
              show-password
            />
          </el-form-item>
          
          <el-form-item prop="agreement">
            <el-checkbox v-model="registerForm.agreement">
              我已阅读并同意
              <el-link type="primary" @click="showTerms">用户协议</el-link> 和 
              <el-link type="primary" @click="showPrivacy">隐私政策</el-link>
            </el-checkbox>
          </el-form-item>
          
          <el-form-item>
            <el-button 
              type="primary" 
              size="large" 
              :loading="loading"
              @click="handleRegister"
              class="register-button"
            >
              注册
            </el-button>
          </el-form-item>
        </el-form>
        
        <div class="login-link">
          <span>已有账号？</span>
          <el-link type="primary" @click="goToLogin">立即登录</el-link>
        </div>
      </div>
    </div>
    <div class="register-right">
      <h2>加入我们</h2>
      <p>开启您的科研数据管理之旅</p>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import AuthAPI from '@/utils/auth'
const router = useRouter()
const registerFormRef = ref(null)
const loading = ref(false)

const registerForm = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  agreement: false
})

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度为3-20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  agreement: [
    { 
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请同意用户协议和隐私政策'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  try {
    await registerFormRef.value.validate()
    loading.value = true
    
    const response = await AuthAPI.register(
      {
        username: registerForm.username,
        email: registerForm.email,
        password: registerForm.password
      }
    )
    localStorage.setItem('token', response.access_token)
    
    // 注册成功后跳转到登录页
    ElMessage.success('注册成功，请登录')
    router.push({name: 'login'})
  } catch (error) {
    console.error('注册失败:', error)
 // 根据错误类型显示不同的错误信息
    if (error.response && error.response.status === 400) {
      // 400错误通常是用户名或邮箱已存在
      if (error.response.data && error.response.data.detail) {
        ElMessage.error(error.response.data.detail)
      } else {
        ElMessage.error('用户名或邮箱已存在')
      }
    } else if (error.message && error.message.includes('Network Error')) {
      // 网络错误
      ElMessage.error('网络连接失败，请检查服务器是否正常运行')
    } else {
      // 其他错误
      ElMessage.error('注册失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

const showTerms = () => {
  ElMessageBox.alert('用户协议内容', '用户协议', {
    confirmButtonText: '确定'
  })
}

const showPrivacy = () => {
  ElMessageBox.alert('隐私政策内容', '隐私政策', {
    confirmButtonText: '确定'
  })
}

const goToLogin = () => {
  router.push({name: 'login'})
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-items: center;
  height: 100vh;
}

.register-left {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.register-form {
  width: 100%;
  max-width: 350px;
}

.register-form h1 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.register-button {
  width: 100%;
}

.login-link {
  text-align: center;
  margin-top: 20px;
}

.register-right {
  flex: 1;
  background: linear-gradient(135deg, #67c23a, #409eff);
  background-image: url('/public/auth-logo.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  color: white;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px;
  text-align: center;
}

.register-right h2 {
  font-size: 28px;
  margin-bottom: 10px;
}

.register-right p {
  font-size: 16px;
  opacity: 0.9;
}

@media (max-width: 768px) {
  .register-container {
    flex-direction: column-reverse;
    height: auto;
  }
  
  .register-right {
    padding: 30px 20px;
  }
  
  .illustration img {
    max-height: 200px;
  }
}
</style>